import React, { useState, useEffect } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Card, Form, Input, Button, Select, message, Space, Row, Col } from 'antd';
import { ArrowLeftOutlined, SaveOutlined, CloseOutlined } from '@ant-design/icons';
import { UserGroup } from '../../g-types/userGroup';
import { UserGroupApi } from './server';
import './index.less';

const { TextArea } = Input;
const { Option } = Select;

/**
 * 用户组详情页面
 */
export const UserGroupDetail: React.FC = () => {
  // 获取路由参数
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  
  // 表单实例
  const [form] = Form.useForm();
  
  // 加载状态
  const [loading, setLoading] = useState<boolean>(false);
  
  // 保存状态
  const [saving, setSaving] = useState<boolean>(false);
  
  // 获取用户组详情
  const fetchUserGroupDetail = async () => {
    // 如果是新建，不需要获取详情
    if (id === 'new') {
      return;
    }
    
    try {
      setLoading(true);
      // 模拟获取用户组详情
      const groupId = parseInt(id as string, 10);
      const mockGroup: UserGroup = {
        id: groupId,
        name: `用户组${groupId}`,
        code: `GROUP_${groupId}`,
        description: `这是用户组${groupId}的描述信息，用于演示用途。`,
        userCount: Math.floor(Math.random() * 100),
        status: groupId % 5 === 0 ? 0 : 1,
        createTime: new Date(Date.now() - groupId * 86400000).toISOString().split('T')[0],
        updateTime: new Date(Date.now() - groupId * 43200000).toISOString().split('T')[0],
      };
      
      // 设置表单初始值
      form.setFieldsValue({
        name: mockGroup.name,
        code: mockGroup.code,
        description: mockGroup.description,
        status: mockGroup.status,
      });
    } catch (error) {
      console.error('获取用户组详情失败', error);
      message.error('获取用户组详情失败');
    } finally {
      setLoading(false);
    }
  };
  
  useEffect(() => {
    fetchUserGroupDetail();
  }, [id]);
  
  // 处理保存
  const handleSave = async () => {
    try {
      await form.validateFields();
      const values = form.getFieldsValue();
      
      setSaving(true);
      
      if (id === 'new') {
        // 创建新用户组
        await UserGroupApi.createUserGroup(values);
        message.success('创建用户组成功');
      } else {
        // 更新用户组
        await UserGroupApi.updateUserGroup({
          id: parseInt(id as string, 10),
          ...values,
        });
        message.success('更新用户组成功');
      }
      
      // 返回列表页
      navigate('/user/group');
    } catch (error) {
      console.error('保存用户组失败', error);
      message.error('保存用户组失败');
    } finally {
      setSaving(false);
    }
  };
  
  // 处理取消
  const handleCancel = () => {
    navigate('/user/group');
  };
  
  return (
    <div className="user-group-detail">
      <Card
        title={`${id === 'new' ? '新建' : '编辑'}用户组`}
        bordered={false}
        loading={loading}
        extra={
          <Space>
            <Button 
              icon={<ArrowLeftOutlined />} 
              onClick={handleCancel}
            >
              返回
            </Button>
          </Space>
        }
      >
        <Form
          form={form}
          layout="vertical"
          initialValues={{ status: 1 }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="名称"
                rules={[
                  { required: true, message: '请输入用户组名称' },
                  { max: 50, message: '名称最多50个字符' },
                ]}
              >
                <Input placeholder="请输入用户组名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="code"
                label="编码"
                rules={[
                  { required: true, message: '请输入用户组编码' },
                  { max: 30, message: '编码最多30个字符' },
                  { pattern: /^[a-zA-Z0-9_]+$/, message: '编码只能包含字母、数字和下划线' },
                ]}
              >
                <Input placeholder="请输入用户组编码" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="description"
            label="描述"
            rules={[
              { max: 200, message: '描述最多200个字符' },
            ]}
          >
            <TextArea placeholder="请输入用户组描述" rows={4} />
          </Form.Item>
          
          <Form.Item
            name="status"
            label="状态"
          >
            <Select placeholder="请选择状态">
              <Option value={1}>启用</Option>
              <Option value={0}>禁用</Option>
            </Select>
          </Form.Item>
          
          <Form.Item>
            <Space>
              <Button
                type="primary"
                icon={<SaveOutlined />}
                onClick={handleSave}
                loading={saving}
              >
                保存
              </Button>
              <Button
                icon={<CloseOutlined />}
                onClick={handleCancel}
              >
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
}; 